home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: a question on "return"
- Date: 4 Feb 1996 08:08:25 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4f2llpINNlve@keats.ugrad.cs.ubc.ca>
- References: <4f2ipq$kaf@srvr1.engin.umich.edu>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4f2ipq$kaf@srvr1.engin.umich.edu>,
- Chih-Jen Lin <cjlin@news-server.engin.umich.edu> wrote:
- >In C, usually we treat 1 as true and 0 as false.
- >However, we usually use return(0) after normal end of an int
- >function and return(1) when some errors happen.
- >Can some one tell me why we return a false value after normal
- >end of a function ?
-
- 1. So you can have a concise, positive test for a failure:
-
- if (myfunc()) {
- /* handle failure */
- }
-
- instead of
-
- if (!myfunc()) {
- /* handle failure */
- }
-
- 2. There are usually(*) more ways to fail than to succeed. Zero
- is unique, non-zero "true" values are abundant. Hence you can use 1 (or
- -1) for one kind of failure, 2 for another and so forth, enabling an
- expression like this:
-
- switch(myfunc()) {
- case -1:
- /* this error */
- break;
- case -2:
- /* that error */
- break;
- case 0:
- /* success */
- break;
- default:
- /* weird */
- break;
- }
-
- (*) Of course, operating system calls like read() have many ways to
- succeed, because they sometimes return a result like the count of bytes
- read. In such a case, negative results can indicate failure, and
- non-negative results success.
- --
-
-